import { useRouteStore } from './route'
import { useTabStore } from './tab'
import { fetchLogin } from '@/service'
import { router } from '@/router'
import { local } from '@/utils'
import { useRoleStore } from '@/store/user'
import avatar from '@/assets/images/avatar.jpg'

interface AuthStatus {
  userInfo: ApiAuth.userInfo | null
  token: string,
  roles: string[],
  permissions: string[]
}
export const useAuthStore = defineStore('auth-store', {
  state: (): AuthStatus => {
    return {
      userInfo: local.get('userInfo') || null,
      token: local.get('token') || '',
      roles: local.get('roles') || [],
      permissions: local.get('permissions') || [],
    }
  },
  getters: {
    /** 是否登录 */
    isLogin(state) {
      return Boolean(state.token)
    },
  },
  actions: {
    /* 登录退出，重置用户信息等 */
    async resetAuthStore() {
      const route = unref(router.currentRoute)
      // 清除本地缓存
      this.clearAuthStorage()
      // 清空路由、菜单等数据
      const routeStore = useRouteStore()
      routeStore.resetRouteStore()
      // 清空标签栏数据
      const tabStore = useTabStore()
      tabStore.clearAllTabs()
      // 重制当前存储库
      this.$reset()
      // 重定向到登录页
      if (route.meta.requiresAuth) {
        router.push({
          name: 'login',
          query: {
            redirect: route.fullPath,
          },
        })
      }
    },
    clearAuthStorage() {
      local.remove('token')
      local.remove('userInfo')
    },

    /* 用户登录 */
    async login(userName: string, password: string) {
      const { isSuccess, token } = await fetchLogin({ userName, password })
      const data = {
        token,
        userName
      }
      if (!isSuccess)
        return
      // 处理登录信息
      await this.handleAfterLogin(data)
    },

    /* 登录后的处理函数 */
    async handleAfterLogin(data: ApiAuth.loginInfo) {
      // 将token和userInfo保存下来
      local.set('token', data.token)
      this.token = data.token

      // 添加路由和菜单
      const routeStore = useRouteStore()
      //获取用户基本信息
      const userInfo = await routeStore.initUserInfo()
      userInfo.user.avatar = avatar
      this.userInfo = userInfo.user
      this.roles = userInfo.roles
      this.permissions = userInfo.permissions
      local.set('userInfo', userInfo.user)
      
      local.set('roles', userInfo.roles)
      local.set('permissions', userInfo.permissions)
      
      // const uStore = useRoleStore()
      // uStore.setRoles(userInfo.roles)
      // uStore.setPermissions(userInfo.permissions)
      // 获取路由
      await routeStore.initAuthRoute()
      // 进行重定向跳转
      const route = unref(router.currentRoute)
      const query = route.query as { redirect: string }
      router.push({
        path: query.redirect || '/',
      })
    },
  },
})
